import React from 'react';
import { useModalStore, type ModalConfig } from '../stores/modalStore';
import { AlertTriangle, Info, XCircle, CheckCircle, X } from 'lucide-react';

const ModalItem: React.FC<{ modal: ModalConfig }> = ({ modal }) => {
  const { closeModal, updateModal } = useModalStore();

  const getIcon = () => {
    switch (modal.type) {
      case 'warning':
        return <AlertTriangle className="w-6 h-6 text-yellow-400" />;
      case 'error':
        return <XCircle className="w-6 h-6 text-red-400" />;
      case 'info':
        return <Info className="w-6 h-6 text-blue-400" />;
      case 'confirm':
        return <CheckCircle className="w-6 h-6 text-green-400" />;
      default:
        return <Info className="w-6 h-6 text-blue-400" />;
    }
  };

  const getIconBgColor = () => {
    switch (modal.type) {
      case 'warning':
        return 'bg-yellow-500/10';
      case 'error':
        return 'bg-red-500/10';
      case 'info':
        return 'bg-blue-500/10';
      case 'confirm':
        return 'bg-green-500/10';
      default:
        return 'bg-blue-500/10';
    }
  };

  const handleConfirm = async () => {
    if (modal.onConfirm) {
      try {
        updateModal(modal.id, { loading: true });
        await modal.onConfirm();
      } catch (error) {
        console.error('Modal confirm error:', error);
      } finally {
        updateModal(modal.id, { loading: false });
      }
    }
    closeModal(modal.id);
  };

  const handleCancel = () => {
    if (modal.onCancel) {
      modal.onCancel();
    }
    closeModal(modal.id);
  };

  return (
    <div className="fixed inset-0 z-[9999] overflow-y-auto">
      {/* 背景遮罩 */}
      <div
        className="fixed inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
        onClick={handleCancel}
      />

      {/* Modal 容器 */}
      <div className="fixed inset-0 z-[10000] overflow-y-auto">
        <div className="flex min-h-full items-center justify-center p-4 text-center sm:p-0">
          {/* Modal 内容 */}
          <div className="relative transform overflow-hidden rounded-lg bg-gray-800 px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6 border border-gray-700">
            <div className="sm:flex sm:items-start">
              <div
                className={`mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full sm:mx-0 sm:h-10 sm:w-10 ${getIconBgColor()}`}
              >
                {getIcon()}
              </div>
              <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
                <h3 className="text-lg leading-6 font-semibold text-white">{modal.title}</h3>
                <div className="mt-2">
                  <p className="text-sm text-gray-300 whitespace-pre-line">{modal.content}</p>
                </div>
              </div>

              {/* 关闭按钮 */}
              <button
                onClick={handleCancel}
                className="absolute top-4 right-4 p-1 rounded-full hover:bg-gray-700 transition-colors cursor-pointer"
              >
                <X className="w-5 h-5 text-gray-400 hover:text-white" />
              </button>
            </div>

            {/* 操作按钮 */}
            <div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse sm:space-x-2 sm:space-x-reverse space-y-2 sm:space-y-0">
              <button
                type="button"
                disabled={modal.loading}
                onClick={handleConfirm}
                className={`
                w-full inline-flex justify-center rounded-lg border border-transparent px-4 py-2 text-base font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 sm:ml-3 sm:w-auto sm:text-sm transition-colors cursor-pointer
                ${
                  modal.type === 'error' || modal.type === 'warning'
                    ? 'bg-red-600 hover:bg-red-700 focus:ring-red-500'
                    : 'bg-blue-600 hover:bg-blue-700 focus:ring-blue-500'
                }
                disabled:opacity-50 disabled:cursor-not-allowed
              `}
              >
                {modal.loading ? (
                  <div className="flex items-center">
                    <svg
                      className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      />
                    </svg>
                    处理中...
                  </div>
                ) : (
                  modal.confirmText
                )}
              </button>

              {modal.showCancel && (
                <button
                  type="button"
                  onClick={handleCancel}
                  className="mt-3 w-full inline-flex justify-center rounded-lg border border-gray-600 bg-gray-700 px-4 py-2 text-base font-medium text-gray-300 shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-800 sm:mt-0 sm:w-auto sm:text-sm transition-colors cursor-pointer"
                >
                  {modal.cancelText}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const ModalContainer: React.FC = () => {
  const { modals } = useModalStore();

  return (
    <>
      {modals.map(modal => (
        <ModalItem key={modal.id} modal={modal} />
      ))}
    </>
  );
};

export default ModalContainer;
